package org.example.company.handler;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;

@Component
public class CustomHttpBasicServerAuthenticationEntryPoint extends HttpBasicServerAuthenticationEntryPoint {
    //重写了认证失败后的响应逻辑。默认情况下，Spring Security 对于 HTTP Basic 认证失败会返回一个空的 401 状态码响应。
    //而通过这个自定义类，认证失败时将返回一个 JSON 响应
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        HashMap<Object, Object> map = new HashMap<>(4);
        map.put("status",HttpStatus.UNAUTHORIZED);
        map.put("massage","鉴权失败");
        byte[] dataBytes = JSON.toJSONString(map).getBytes();
        //将字节数组 dataBytes 包装到该缓冲区中。
        DataBuffer dataBuffer = response.bufferFactory().wrap(dataBytes);
        return response.writeWith(Mono.just(dataBuffer));
    }
}
